package com.dk.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager ){

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        Map<String,String> map = new LinkedHashMap<>();

        map.put("/","anon");//登录页面,

        map.put("/js/**","anon");//js

        map.put("/css/**","anon");//css

        map.put("/person/getInfoById","anon");//登录

        map.put("/code/vcode","anon");//验证码

        /*map.put("/select","anon");//查询放过

        map.put("/index","anon");//主页面

        map.put("/delete","perms[a-delete]");//删除加权限*/

        map.put("/menu/toShow","perms[menu_toShow]");//删除加权限

        map.put("/person/toAdd","perms[person_add]");//用户增加权限

        map.put("/loginOut","logout");//退出登录

        map.put("/**","authc");//全部拦截

        shiroFilterFactoryBean.setUnauthorizedUrl("/person/Unauthorized");//错误页面

        shiroFilterFactoryBean.setLoginUrl("/person/toLogin");//登录页面

        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        return shiroFilterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired ShiroRealm shiroRealm){

        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        defaultWebSecurityManager.setRealm(shiroRealm);//安全管理器,关联登录权限

        return defaultWebSecurityManager;
    }

    @Bean
    public ShiroRealm shiroRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){

        ShiroRealm shiroRealm = new ShiroRealm();

        shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher);

        return shiroRealm;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){

        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();

        matcher.setHashAlgorithmName("MD5");//加密方式

        matcher.setHashIterations(3);//盐

        matcher.setStoredCredentialsHexEncoded(true);//开启编码

        return matcher;
    }


    @Bean
    public ShiroDialect shiroDialect(){

        return new ShiroDialect();
    }

}
